package com.hbnu.util;

import com.hbnu.tourist.domain.Tourist;
import com.hbnu.util.Jwt;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class JwtTouristFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    // 放行路径定义（可以根据你系统修改）
    private static final String[] PUBLIC_PATHS = {"/tourists/login", "/tourists/register","/tourists/captchaImage","/tourists/updatePassword","/tourists/getCode","/tourists/findPassword",
            "/prod-api/**",
//            "/swagger",
            "/",
            "/*.html",
            "/**/*.html",
            "/**/*.css",
            "/**/*.js",
            "/profile/**",
            "/swagger-ui.html",
            "/swagger-resources/**",
            "/webjars/**",
            "/*/api-docs",
            "/druid/**"

    };
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        String path = request.getRequestURI();
        System.out.println("path:"+path);
        System.out.println("token:"+token);
        if (isPublicPath(path)) {
            System.out.println("放行");
            filterChain.doFilter(request, response);
            return;
        }

        // token 为空，拦截返回 401
        if (token == null) {
            throw new BadCredentialsException("缺少 token");
        }
        String id;
        try {
            Map<String, Object> stringObjectMap = Jwt.parseJwt(token);
            id = stringObjectMap.get("id").toString();
        }catch (Exception e){
            e.printStackTrace();
            throw new BadCredentialsException("token 无效");
        }
        String redisKey = "login:"+id;
        Tourist loginUser = redisCache.getCacheObject(redisKey);
        if (loginUser == null) {
            throw new DisabledException("登录信息已过期");
        }
        UsernamePasswordAuthenticationToken  authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
    // 简单路径匹配，可替换为 AntPathMatcher、正则或配置文件
    private boolean isPublicPath(String path) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String publicPath : PUBLIC_PATHS) {
            if (pathMatcher.match(publicPath, path)) {
                System.out.println("匹配成功");
                return true;
            }
        }
        System.out.println("匹配失败");
        return false;
    }
}
